/**
* \mainpage Interface
*
*
*
* \section intro_sec Introducao
*
*   Interface do Candelabro\n
*
* \section hist_sec Historico
*
* @header      interface.h
* @version     1.0
* @date        1/12/2010
* @author      Fernando Alberto C. dos S. Junior
* @group       UEFS - Engenharia da Computacao
* @see         Projeto Anual I - Prof. Angelo Duarte\n Candelabro
* @link        Repositorio <http://candelabro.googlecode.com/svn/trunk/candelabro>
* @ref         Candelabro::Interface
*
*/

#include <interface.h>
#include <QDesktopWidget>
#include <list>
#include <indiceapp.h>
#include <adx.h>
#include <listaadx.h>
#include "estocastico.h"

#include <QDebug>


#include "dialogoimportacao.h"

/**
* Inicializacao da interface
* @param MainWindow referencia a uma MainWindow
*/

void Interface::setupUi()
    {

    this->db = new CandelabroDB();
    this->db->openDatabase();

    inicializarVariaveis();
    if (this->objectName().isEmpty())
        this->setObjectName(QString::fromUtf8("Candelabro 0.3"));
    this->resize(w, h);
    QPalette palette;

    // A aplicacao soh utiliza dois tipos de pincel, branco ou preto
    QBrush brush(QColor(0, 0, 0, 255)); //preto
    brush.setStyle(Qt::SolidPattern);   //branco
    palette.setBrush(QPalette::Active, QPalette::WindowText, brush);
    QBrush brush1(QColor(255, 255, 255, 255));
    //estilo da mainwindow
    brush1.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::Base, brush1);
    palette.setBrush(QPalette::Active, QPalette::Window, brush);
    palette.setBrush(QPalette::Inactive, QPalette::WindowText, brush);
    palette.setBrush(QPalette::Inactive, QPalette::Base, brush1);
    palette.setBrush(QPalette::Inactive, QPalette::Window, brush);
    QBrush brush2(QColor(112, 111, 113, 255));
    brush2.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Disabled, QPalette::WindowText, brush2);
    palette.setBrush(QPalette::Disabled, QPalette::Base, brush);
    palette.setBrush(QPalette::Disabled, QPalette::Window, brush);
    this->setPalette(palette);
    //actions
    actionFechar = new QAction(this);
    actionFechar->setObjectName(QString::fromUtf8("actionFechar"));
    centralwidget = new QWidget(this);
    centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
    gridLayout_6 = new QGridLayout(centralwidget);
    gridLayout_6->setObjectName(QString::fromUtf8("gridLayout_6"));
    //Pallete1 e 3 define todo o estilo da aplicacao
    QPalette palette1;
    palette1.setBrush(QPalette::Active, QPalette::WindowText, brush1);
    palette1.setBrush(QPalette::Active, QPalette::Button, brush1);
    palette1.setBrush(QPalette::Active, QPalette::Text, brush);
    palette1.setBrush(QPalette::Active, QPalette::ButtonText, brush);
    palette1.setBrush(QPalette::Active, QPalette::Highlight, brush);
    palette1.setBrush(QPalette::Active, QPalette::AlternateBase, brush);
    palette1.setBrush(QPalette::Inactive, QPalette::WindowText, brush1);
    palette1.setBrush(QPalette::Inactive, QPalette::Button, brush1);
    palette1.setBrush(QPalette::Inactive, QPalette::Text, brush);
    palette1.setBrush(QPalette::Inactive, QPalette::ButtonText, brush);
    palette1.setBrush(QPalette::Inactive, QPalette::Highlight, brush);
    palette1.setBrush(QPalette::Inactive, QPalette::AlternateBase, brush);
    palette1.setBrush(QPalette::Disabled, QPalette::WindowText, brush1);
    palette1.setBrush(QPalette::Disabled, QPalette::Button, brush1);
    palette1.setBrush(QPalette::Disabled, QPalette::Text, brush);
    palette1.setBrush(QPalette::Disabled, QPalette::ButtonText, brush);
    palette1.setBrush(QPalette::Disabled, QPalette::Base, brush);
    palette1.setBrush(QPalette::Disabled, QPalette::Light, brush);
    QPalette palette3;
    palette3.setBrush(QPalette::Active, QPalette::WindowText, brush1);
    palette3.setBrush(QPalette::Active, QPalette::Button, brush1);
    palette3.setBrush(QPalette::Active, QPalette::Text, brush1);
    //fim das Pallets
    //groupBox da lateral
    mainBox = new QGroupBox(centralwidget);
    mainBox->setObjectName(QString::fromUtf8("mainBox"));
    verticalBox = new QVBoxLayout(mainBox);
    verticalBox->setObjectName(QString::fromUtf8("verticalBox"));
    boxIntervalo = new QGroupBox(mainBox);
    boxIntervalo->setObjectName(QString::fromUtf8("boxIntervalo"));
    boxIntervalo->setFlat(false);
    boxIntervalo->setCheckable(false);
    gridBox3 = new QGridLayout(boxIntervalo);
    gridBox3->setObjectName(QString::fromUtf8("gridBox3"));
    SliderIntervalo = new QwtSlider(boxIntervalo);
    SliderIntervalo->setObjectName(QString::fromUtf8("SliderIntervalo"));
    gridBox3->addWidget(SliderIntervalo, 0, 0, 1, 1);
    labelBox = new QLabel(boxIntervalo);
    labelBox->setObjectName(QString::fromUtf8("labelBox"));
    gridBox3->addWidget(labelBox, 1, 0, 1, 1);
    verticalBox->addWidget(boxIntervalo);
    boxAcao = new QGroupBox(mainBox);
    boxAcao->setObjectName(QString::fromUtf8("boxAcao"));
    gridBox4 = new QGridLayout(boxAcao);
    gridBox4->setObjectName(QString::fromUtf8("gridBox4"));
    comboAcao = new QComboBox(boxAcao);
    comboAcao->setObjectName(QString::fromUtf8("comboAcao"));
    gridBox4->addWidget(comboAcao, 0, 0, 1, 1);
    l_intervalo_acao = new QLabel(boxAcao);
    l_intervalo_acao->setObjectName(QString::fromUtf8("intervalo"));
    l_intervalo_acao->setAlignment(Qt::AlignCenter);
    l_intervalo_acao->setText(QString::fromUtf8("Quantidade de meses"));
    gridBox4->addWidget(l_intervalo_acao,1,0,1,1);
    intervalo_acao = new QSpinBox(boxAcao);
    intervalo_acao->setObjectName(QString::fromUtf8("intervalo_acao"));
    gridBox4->addWidget(intervalo_acao,1,1,1,1);
    verticalBox->addWidget(boxAcao);
    //bandas de boillinger
    bandas = new QGroupBox(mainBox);
    bandas->setTitle("Bandas de Boillinger");
    gridLayout_bandas = new QGridLayout(bandas);
    l_bandas = new QLabel(didi);
    l_bandas->setText(QString::fromUtf8("Período"));
    gridLayout_bandas->addWidget(l_bandas, 0, 0, 1, 1);
    sb_bandas = new QSpinBox(didi);
    gridLayout_bandas->addWidget(sb_bandas, 0, 1, 1, 1);
    verticalBox->addWidget(bandas);
    //didi
    didi = new QGroupBox(mainBox);
    didi->setTitle("Didi");
    gridLayout_gb1 = new QGridLayout(didi);
    l_didi1 = new QLabel(didi);
    l_didi1->setText("Curta");
    gridLayout_gb1->addWidget(l_didi1, 0, 0, 1, 1);
    l_didi2 = new QLabel(didi);
    l_didi2->setText(QString::fromUtf8("Média"));
    gridLayout_gb1->addWidget(l_didi2, 0, 3, 1, 1);
    l_didi3 = new QLabel(didi);
    l_didi3->setText("Longa");
    gridLayout_gb1->addWidget(l_didi3, 0, 7, 1, 1);
    sb_didi1 = new QSpinBox(didi);
    gridLayout_gb1->addWidget(sb_didi1, 0, 1, 1, 1);
    sb_didi2 = new QSpinBox(didi);
    gridLayout_gb1->addWidget(sb_didi2, 0, 5, 1, 1);
    sb_didi3 = new QSpinBox(didi);
    gridLayout_gb1->addWidget(sb_didi3, 0, 8, 1, 1);
    hS_didi1 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    gridLayout_gb1->addItem(hS_didi1, 0, 2, 1, 1);
    hS_didi2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    gridLayout_gb1->addItem(hS_didi2, 0, 6, 1, 1);
    verticalBox->addWidget(didi);
    //trix
    trix = new QGroupBox(mainBox);
    trix->setTitle("trix");
    gridLayout_trix = new QGridLayout(trix);
    l_trix1 = new QLabel(trix);
    l_trix1->setText(QString::fromUtf8("Período"));
    gridLayout_trix->addWidget(l_trix1, 0, 0, 1, 1);
    l_trix2 = new QLabel(trix);
    l_trix2->setText(QString::fromUtf8("Intervalo"));
    gridLayout_trix->addWidget(l_trix2, 0, 2, 1, 1);
    sb_trix1 = new QSpinBox(trix);
    gridLayout_trix->addWidget(sb_trix1, 0, 1, 1, 1);
    sb_trix2 = new QSpinBox(trix);
    gridLayout_trix->addWidget(sb_trix2, 0, 4, 1, 1);
    hS_trix1 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    gridLayout_trix->addItem(hS_trix1, 0, 1, 1, 1);
    hS_trix2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    gridLayout_trix->addItem(hS_trix2, 0, 4, 1, 1);
    verticalBox->addWidget(trix);
    //adx
    adx = new QGroupBox(mainBox);
    adx->setTitle("ADX");
    gridLayout_adx1 = new QGridLayout(adx);
    l_adx1 = new QLabel(adx);
    l_adx1->setText(QString::fromUtf8("Período"));
    gridLayout_adx1->addWidget(l_adx1, 0, 0, 1, 1);
    sb_adx1 = new QSpinBox(adx);
    gridLayout_adx1->addWidget(sb_adx1, 0, 1, 1, 1);
    verticalBox->addWidget(adx);
    //estocastico
    est = new QGroupBox(mainBox);
    est->setTitle(QString::fromUtf8("Estocástico"));
    gridLayout_est = new QGridLayout(est);
    l_est = new QLabel(est);
    l_est->setText(QString::fromUtf8("Período"));
    gridLayout_est->addWidget(l_est, 0, 0, 1, 1);
    sb_est = new QSpinBox(est);
    gridLayout_est->addWidget(sb_est, 0, 1, 1, 1);
    verticalBox->addWidget(est);
    gridLayout_6->addWidget(mainBox, 0, 0, 1, 1);
    mainBox->setPalette(palette1);
    //fim da group box lateral

    this->setCentralWidget(centralwidget);
    menubar = new QMenuBar(this);
    menubar->setObjectName(QString::fromUtf8("menubar"));
    menubar->setGeometry(QRect(0, 0, w, 20));
    menuArquivo = new QMenu(menubar);
    menuArquivo->setObjectName(QString::fromUtf8("menuArquivo"));
    this->setMenuBar(menubar);
    statusbar = new QStatusBar(this);
    statusbar->setObjectName(QString::fromUtf8("statusbar"));
    this->setStatusBar(statusbar);
    dock1 = new QDockWidget(this);
    dock1->setObjectName(QString::fromUtf8("dock1"));
    dock1->setEnabled(true);
    dock1->setMinimumSize(QSize(w_dock, 15));
    QBrush brush3(QColor(178, 180, 191, 255));
    brush3.setStyle(Qt::SolidPattern);
    palette1.setBrush(QPalette::Disabled, QPalette::Highlight, brush3);
    palette1.setBrush(QPalette::Disabled, QPalette::AlternateBase, brush);
    dock1->setPalette(palette1);
    dock1->setFloating(false);
    dock1->setFeatures(QDockWidget::DockWidgetMovable);
    dock1->setAllowedAreas(Qt::LeftDockWidgetArea);
    dockWidgetContents = new QWidget();
    dockWidgetContents->setObjectName(QString::fromUtf8("dockWidgetContents"));
    gridLayout = new QGridLayout(dockWidgetContents);
    gridLayout->setContentsMargins(0, 0, 0, 0);
    gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
    gridLayout->setHorizontalSpacing(3);
    gridLayout->setVerticalSpacing(0);

    //QWTPLOT-CANDLESTICK
    qwtPlot = new Plot(dockWidgetContents); // parent dockWidgetContents
    qwtPlot->setMinimumHeight(3); // completely hide the qwtplot
    qwtPlot->minimumSize();// allow the minimun size
    qwtPlot->setPalette(palette3);

    gridLayout->addWidget(qwtPlot, 0, 0, 1, 1); // insert into the first line (line 0) of the grid

    dock1->setWidget(dockWidgetContents);
    this->addDockWidget(static_cast<Qt::DockWidgetArea>(1), dock1);

    //DOCK2
    dock2 = new QDockWidget(this);
    dock2->setObjectName(QString::fromUtf8("dock2"));
    dock2->setMinimumSize(QSize(w_dock, 15));
    dock2->setPalette(palette1);
    dock2->setAllowedAreas(Qt::LeftDockWidgetArea);
    dock2->setFeatures(QDockWidget::DockWidgetMovable);
    dockWidgetContents_2 = new QWidget();
    dockWidgetContents_2->setObjectName(QString::fromUtf8("dockWidgetContents_2"));
    gridLayout_2 = new QGridLayout(dockWidgetContents_2);
    gridLayout_2->setSpacing(0);
    gridLayout_2->setContentsMargins(0, 0, 0, 0);
    gridLayout_2->setObjectName(QString::fromUtf8("gridLayout_2"));

    qwtPlot_3 = new Plot(dockWidgetContents_2);
    qwtPlot_3->setMinimumHeight(3);
    qwtPlot_3->minimumSize();
    qwtPlot_3->setPalette(palette3);

    gridLayout_2->addWidget(qwtPlot_3, 0, 0, 1, 1);

    dock2->setWidget(dockWidgetContents_2);
    this->addDockWidget(static_cast<Qt::DockWidgetArea>(1), dock2);

    //dock 3
    dock3 = new QDockWidget(this);
    dock3->setObjectName(QString::fromUtf8("dock3"));
    dock3->setMinimumSize(QSize(w_dock, 15));
    dock3->setPalette(palette1);
    dock3->setAllowedAreas(Qt::LeftDockWidgetArea);
    dock3->setFeatures(QDockWidget::DockWidgetMovable);
    dockWidgetContents_3 = new QWidget();
    dockWidgetContents_3->setObjectName(QString::fromUtf8("dockWidgetContents_3"));
    gridLayout_3 = new QGridLayout(dockWidgetContents_3);
    gridLayout_3->setSpacing(0);
    gridLayout_3->setContentsMargins(0, 0, 0, 0);
    gridLayout_3->setObjectName(QString::fromUtf8("gridLayout_3"));

    qwtPlot_2 = new Plot(dockWidgetContents_3);
    qwtPlot_2->setMinimumHeight(3);
    qwtPlot_2->minimumSize();
    qwtPlot_2->setPalette(palette3);

    gridLayout_3->addWidget(qwtPlot_2, 0, 0, 1, 1);

    dock3->setWidget(dockWidgetContents_3);
    this->addDockWidget(static_cast<Qt::DockWidgetArea>(1), dock3);

    //dock 4
    dock4 = new QDockWidget(this);
    dock4->setObjectName(QString::fromUtf8("dock4"));
    dock4->setMinimumSize(QSize(w_dock, 15));
    dock4->setPalette(palette1);
    dock4->setAllowedAreas(Qt::LeftDockWidgetArea);
    dock4->setFeatures(QDockWidget::DockWidgetMovable);
    dockWidgetContents_4 = new QWidget();
    dockWidgetContents_4->setObjectName(QString::fromUtf8("dockWidgetContents_4"));
    gridLayout_4 = new QGridLayout(dockWidgetContents_4);
    gridLayout_4->setSpacing(0);
    gridLayout_4->setContentsMargins(0, 0, 0, 0);
    gridLayout_4->setObjectName(QString::fromUtf8("gridLayout_4"));

    qwtPlot_4 = new Plot(dockWidgetContents_4);
    qwtPlot_4->setMinimumHeight(3);
    qwtPlot_4->minimumSize();
    qwtPlot_4->setPalette(palette3);
    gridLayout_4->addWidget(qwtPlot_4, 0, 0, 1, 1);

    dock4->setWidget(dockWidgetContents_4);
    this->addDockWidget(static_cast<Qt::DockWidgetArea>(1), dock4);

    //dock 5
    dock5 = new QDockWidget(this);
    dock5->setObjectName(QString::fromUtf8("dock5"));
    dock5->setMinimumSize(QSize(w_dock, 15));
    dock5->setPalette(palette1);
    dock5->setAllowedAreas(Qt::LeftDockWidgetArea);
    dock5->setFeatures(QDockWidget::DockWidgetMovable);
    dockWidgetContents_5 = new QWidget();
    dockWidgetContents_5->setObjectName(QString::fromUtf8("dockWidgetContents_5"));
    gridLayout_5 = new QGridLayout(dockWidgetContents_5);
    gridLayout_5->setSpacing(0);
    gridLayout_5->setContentsMargins(0, 0, 0, 0);
    gridLayout_5->setObjectName(QString::fromUtf8("gridLayout_5"));

    qwtPlot_5 = new Plot(dockWidgetContents_5);
    qwtPlot_5->setMinimumHeight(3);
    qwtPlot_5->minimumSize();
    qwtPlot_5->setPalette(palette3);

    gridLayout_5->addWidget(qwtPlot_5, 0, 0, 1, 1);

    dock5->setWidget(dockWidgetContents_5);
    this->addDockWidget(static_cast<Qt::DockWidgetArea>(1), dock5);
    slider = new QDockWidget(this);
    slider->setObjectName(QString::fromUtf8("slider"));
    slider->setMinimumSize(QSize(w_dock, 50));
    slider->setMaximumSize(QSize(524287, 50));
    slider->setPalette(palette1);
    slider->setFeatures(QDockWidget::NoDockWidgetFeatures);
    slider->setAllowedAreas(Qt::LeftDockWidgetArea);
    dockWidgetContents_7 = new QWidget();
    dockWidgetContents_7->setObjectName(QString::fromUtf8("dockWidgetContents_7"));
    gridLayout_8 = new QGridLayout(dockWidgetContents_7);
    gridLayout_8->setContentsMargins(0, 0, 0, 0);
    gridLayout_8->setObjectName(QString::fromUtf8("gridLayout_8"));
    gridLayout_8->setHorizontalSpacing(0);
    Slider_2 = new QwtSlider(dockWidgetContents_7);
    Slider_2->setObjectName(QString::fromUtf8("Slider_2"));
    Slider_2->setPalette(palette1);

    gridLayout_8->addWidget(Slider_2, 0, 0, 1, 1);

    slider->setWidget(dockWidgetContents_7);
    this->addDockWidget(static_cast<Qt::DockWidgetArea>(1), slider);

    menubar->addAction(menuArquivo->menuAction());
    menuArquivo->addAction(actionFechar);
    retranslateUi();

    //cria conexoes com os slots
    QObject::connect(SliderIntervalo, SIGNAL(sliderMoved(double)), this, SLOT(setIntervalo(double)));
    QObject::connect(Slider_2, SIGNAL(valueChanged(double)), this, SLOT(setAxisMinMax(double)));
    QObject::connect(sb_bandas, SIGNAL(valueChanged(int)), this, SLOT(setVariaveis()));
    QObject::connect(sb_didi1, SIGNAL(valueChanged(int)), this, SLOT(setVariaveis()));
    QObject::connect(sb_didi2, SIGNAL(valueChanged(int)), this, SLOT(setVariaveis()));
    QObject::connect(sb_didi3, SIGNAL(valueChanged(int)), this, SLOT(setVariaveis()));
    QObject::connect(sb_adx1, SIGNAL(valueChanged(int)), this, SLOT(setVariaveis()));
    QObject::connect(sb_trix1, SIGNAL(valueChanged(int)), this, SLOT(setVariaveis()));
    QObject::connect(sb_trix2, SIGNAL(valueChanged(int)), this, SLOT(setVariaveis()));
    QObject::connect(sb_est, SIGNAL(valueChanged(int)), this, SLOT(setVariaveis()));


    QMetaObject::connectSlotsByName(this);



    atualizarBoxAcao();
    configurarComboboxAcao();
    configurarMenuImportacao();



    setDataCandleStick(this->comboAcao->currentText() , 6);
    //tooltips
    Slider_2->setValue(100.0);
    Slider_2->setToolTip(QString::fromUtf8("Arraste a barra para variar os intervalos"));
    sb_bandas->setValue(8);
    sb_bandas->setToolTip(QString::fromUtf8("Períodoa que será utilizado para determinar as Bandas de Boillinger"));
    sb_didi1->setValue(3);
    sb_didi1->setToolTip((QString::fromUtf8("Período para calculo da média curta")));
    sb_didi2->setValue(8);
    sb_didi2->setToolTip((QString::fromUtf8("Período para calculo da média intermediária")));
    sb_didi3->setValue(20);
    sb_didi3->setToolTip((QString::fromUtf8("Período para calculo da média longa")));
    sb_adx1->setValue(8);
    sb_adx1->setToolTip((QString::fromUtf8("Periódo que será utilizado no calculo ADX")));
    sb_trix1->setValue(5);
    sb_trix2->setValue(5);
    intervalo_acao->setValue(6);
    intervalo_acao->setToolTip(QString::fromUtf8("Quantidade de meses"));
    sb_est->setValue(7);


} // setupUi

/**
* Inicializa as variaveis de controle do ambiente
*/
void Interface::inicializarVariaveis(){
    QDesktopWidget *d = QApplication::desktop();
    // capitura a dimensao da tela
    w = d->width();     // retorna a largura
    h = d->height();    // retorna a altura
    w_dock = w*0.75;// valor da largura minima de uma dock
    //dandas de boillinger
    bb_periodo = 8;
    //didi
    didi_curta = 3;
    didi_inter = 8;
    didi_longa = 20;
    //ADX
    adx_periodo = 8;
    //TRIX
    trix_n_dias = 5;
    trix_q_dias = 5;
    inter_acao = 100;
    est_periodo = 7;
}
/**
* Slot. Atualiza a combo box e a cada nova selecao ou modificacao na quantidade de meses/n
* ele chama o metodo de acesso ao banco
*/
void Interface::configurarComboboxAcao()
{
    this->comboAcao->addItems(db->getPricedStocksNames());
    connect(this->comboAcao, SIGNAL(currentIndexChanged(int)), this, SLOT(mudarAcaoDaTela()));
    connect(this->intervalo_acao, SIGNAL(valueChanged(int)), this, SLOT(mudarAcaoDaTela()));
}
/**
* Slot. Chama o metodo abrirJanelaImportacaoParaBanco()
*/
void Interface::configurarMenuImportacao()
{
    actionImportToDatabase = new QAction("Importar para o banco de dados", this);
    menuArquivo->addAction(actionImportToDatabase);
    connect(actionImportToDatabase, SIGNAL(triggered()), this, SLOT(abrirJanelaImportacaoParaBanco()) );
}
/**
* Chama a janela de importacao de dados para o banco
*/
void Interface::abrirJanelaImportacaoParaBanco()
{
    DialogoImportacao *diag_import = new DialogoImportacao(this);
    QObject::connect(diag_import, SIGNAL(acaoFoiInserida()), this, SLOT(atualizarBoxAcao()));
    diag_import->setDatabase(db);
    diag_import->show();
}
/**
* Atualiza os dados - retorna informaçoes do banco
*/
void Interface::mudarAcaoDaTela()
{
    setDataCandleStick(this->comboAcao->currentText(), (int) intervalo_acao->value());
}

/**
* Slot - atualiza o intervalo
* @param Slider valor retornado pelo slider
*/
void Interface::setIntervalo(double Slider){
    double sl = Slider;
    sl = sl < 2 ? 2: sl;
    //sl = 100.0 - sl;
    sl = sl/100; //sl agora é um valor percentual
    intervalo = (int) data_db.size()*sl;
    if(intervalo <=26){
        intervalo = 26;
    }
    labelBox->setNum(intervalo);
    setAxisMinMax(sliderValorOrig);
}
/**
* Slot - atualiza o parametro da banda de boillinger
* @param x valor retornado pela interface
*/
void Interface::setBandasPeriodo(int x){
    //boillinger
    bb_periodo = x;
    setAxisMinMax(sliderValorOrig);
}
/**
* Slot - atualiza os parametros utilizado nos calculos dos graficos
*/
void Interface::setVariaveis(){
    //boillinger
    bb_periodo = sb_bandas->value();
    //didi
    if (sb_didi2->value() <= sb_didi1->value()+1){
        sb_didi2->setValue(sb_didi1->value()+1);
    }
    if (sb_didi3->value() <= sb_didi2->value()+1){
        sb_didi3->setValue(sb_didi2->value()+1);
    }
    didi_curta = sb_didi1->value();
    didi_inter = sb_didi2->value();
    didi_longa = sb_didi3->value();
    //ADX
    adx_periodo = sb_adx1->value();
    //TRIX
    trix_n_dias = sb_trix1->value();

    trix_q_dias = sb_trix2->value();

    est_periodo = sb_est->value();

    setAxisMinMax(sliderValorOrig);
}
/**
* Slot - atualiza os intervalos que serao exibidos
* @param Slider valor retornado pelo slider
*/
void Interface::setAxisMinMax(double Slider){
    if ((int) intervalo_acao->value() > 10){
        qwtPlot->setAxisMaxMajor(Plot::xBottom,(int)intervalo_acao->value()*4);
        qwtPlot_2->setAxisMaxMajor(Plot::xBottom,(int)intervalo_acao->value()*4);
        qwtPlot_3->setAxisMaxMajor(Plot::xBottom,(int)intervalo_acao->value()*4);
        qwtPlot_4->setAxisMaxMajor(Plot::xBottom,(int)intervalo_acao->value()*4);
        qwtPlot_5->setAxisMaxMajor(Plot::xBottom,(int)intervalo_acao->value()*4);
    } else {
        qwtPlot->setAxisMaxMajor(Plot::xBottom,intervalo);
        qwtPlot_2->setAxisMaxMajor(Plot::xBottom,intervalo);
        qwtPlot_3->setAxisMaxMajor(Plot::xBottom,intervalo);
        qwtPlot_4->setAxisMaxMajor(Plot::xBottom,intervalo);
        qwtPlot_5->setAxisMaxMajor(Plot::xBottom,intervalo);
    }

    sliderValorOrig = Slider;
    sliderMaior = Slider;
    sliderMaior = sliderMaior/100; //sl agora é um valor percentual
    int valorMin;
    int intervaloData = data_db.size()-intervalo;
    valorMin = (int) intervaloData*sliderMaior;

    qwtPlot->limpa();
    qwtPlot_2->limpa();
    qwtPlot_3->limpa();
    qwtPlot_4->limpa();
    qwtPlot_5->limpa();

    setData(valorMin, intervalo);
}
/**
* Atualiza os dados com as informaçoes retorndadas do banco/n
* @param nome nome do papel
* @param periodo quantdade de dias
*/
void Interface::setDataCandleStick(QString nome, int periodo){

    periodo = periodo < 3 ? 3 : periodo;

    db->openDatabase();
    QDate inicio = QDate::currentDate().addMonths(-periodo);//.addMonths(-6);
    QDate fim    = QDate::currentDate();

    data_db = db->getStockPrices(nome, inicio, fim);

    int aux = (int) data_db.size()*0.7;
    intervalo = aux;
    setData(0, data_db.size());
    SliderIntervalo->setValue(70);
    setIntervalo(70);
}

/**
* Atualiza a interface com as informaçoes retorndadas do banco/n
* @param ponteiro primeiro dia
* @param intervalo intervalo de dias que serão plotados
*/
void Interface::setData(int ponteiro, int intervalo){
    //CandleStick
    QwtArray<QwtPriceMove> sample(intervalo);
    QwtArray<QwtDoubleInterval> datas(intervalo);
    QwtArray<QwtDoublePoint> MaxMin(intervalo);
    //didi de boilinger
    double bb_fechamento[intervalo];

    //controle
    QwtArray<QwtDoublePoint> controle(intervalo);
    //didi
    list<Indice*> lista_didi(intervalo);
    list<Indice*> lista_didi_resp(intervalo);
    //ADX
    list<ADX*> lista_adx(intervalo);

    //estocastico
    double estocastico_maximo[intervalo];
    double estocastico_minimo[intervalo];
    double estocastico_fechamento[intervalo];


    int i=0;  //um dia eh igural a: 201000105214460
    for (i=0; i<intervalo;i++)
    {
        controle[i] = QwtDoublePoint(i, 0);
        double alta = data_db.at(i+ponteiro).high;
        double baixa = data_db.at(i+ponteiro).low;
        double fechamento = data_db.at(i+ponteiro).close;
        QString data = toDateTime(datas.at(i));//didi
        //didi
        lista_didi.pop_back();
        lista_didi.push_front(new Indice(data, fechamento, 0,0,0,0,0,0));//didi
        MaxMin[i] = QwtDoublePoint(fechamento,  data_db.at(i+ponteiro).high);
        //datas
        datas[i]= QwtDoubleInterval(data_db.at(i+ponteiro).unixdate,data_db.at(i+ponteiro).unixdate+86400);
        //candles
        sample[i].interval = QwtDoubleInterval(i+ponteiro, i+ponteiro+1); //86400 é o intervalo de um dia em segundos
        sample[i].open = data_db.at(i+ponteiro).open;
        sample[i].close = fechamento;
        sample[i].high = data_db.at(i+ponteiro).high;
        sample[i].low = data_db.at(i+ponteiro).low;
        //didi de boillinger
        bb_fechamento[i] = fechamento;
        estocastico_maximo[i] = data_db.at(i+ponteiro).high;
        estocastico_minimo[i] = data_db.at(i+ponteiro).low;
        estocastico_fechamento[i] = fechamento;
        //adx
        lista_adx.pop_back();
        lista_adx.push_front(new ADX(data.toStdString(), alta, baixa, fechamento));
    }

    //banda de Bollinger
    BollingerBands *bb = new BollingerBands;

    int bb_tamanho = intervalo + bb_periodo;

    bb_tamanho = bb_tamanho + ponteiro >= data_db.size() ? data_db.size()- ponteiro : bb_tamanho;

    double bb_fechament[bb_tamanho];
    for (i = 0 ; i < bb_tamanho ; i++){
        bb_fechament[i] = data_db.at(i+ponteiro).close;
    }

    bb->bollingerBandesCalc(bb_fechament, bb_tamanho, bb_periodo);
    double bs2=0;
    double bi2=0;
    double *bs = bb->bandaSuperior;
    double *bi = bb->bandaInferior;
    if (bb_periodo<bb_tamanho){ //se nao foi definido um periodo maior que o intervalo de dados a ser plotados...
        QwtArray<QwtDoublePoint> bb_bs(bb_tamanho-bb_periodo);
        QwtArray<QwtDoublePoint> bb_bi(bb_tamanho-bb_periodo);
        for(i=0; i<bb_tamanho-bb_periodo; i++){
            bs2 = bs[i] == 0 ? bs2 : bs[i];
            bi2 = bi[i] == 0 ? bi2 : bi[i];
            bb_bs[i] = QwtDoublePoint((double)i+ponteiro+bb_periodo, bs2);
            bb_bi[i] = QwtDoublePoint((double)i+ponteiro+bb_periodo, bi2);
        }

        qwtPlot->setData(&sample, &bb_bs, &bb_bi, &MaxMin);
        qwtPlot->replot();
    }

    //DIDI
    IndiceApp *didi = new IndiceApp();
    lista_didi_resp = didi->calculaDIDI(didi_curta,didi_inter,didi_longa,lista_didi);
    Indice *objeto = new Indice();
    list<Indice*>::iterator iter = lista_didi_resp.end();
    int x=0;
    double  x1=0; // Como os ultimos valores poderao ser preenchidos com 0
    double  x2=0; // estas variaveis sao utilizadas neste contreole para que
    double di3=0, x3=0; // no lugar do zero seja armazenado o ultimo valor (x e y) valido
    if (didi_curta < intervalo && didi_inter < intervalo && didi_longa < intervalo){
        QwtArray<QwtDoublePoint> didi1(intervalo);
        QwtArray<QwtDoublePoint> didi2(intervalo);
        QwtArray<QwtDoublePoint> didi3(intervalo);
        while (iter != lista_didi_resp.begin())
        {
            objeto = *iter;
            didi1[x] = QwtDoublePoint((double) x, objeto->curta);
            didi2[x] = QwtDoublePoint((double) x, objeto->longa);
            didi3[x] = QwtDoublePoint((double) x, 1.0);
            iter--;
            x++;
        }
        for (i = 0; i < didi_longa; i++){
            didi1[i] = didi1[didi_longa];
            didi2[i] = didi2[didi_longa];
        }

        qwtPlot_3->setData(&didi1, &didi2, &didi3);
        qwtPlot_3->replot();
    }
    x=x1=x2=x3=0;
    //END DIDI

    //ADX
    ListaADX *adx = new ListaADX;
    list<ADX*> lista_adx_resp(lista_adx.size());
    lista_adx_resp = adx->calculaADX(adx_periodo, lista_adx);
    ADX *objeto2 = new ADX();
    list<ADX*>::iterator iter_2 = lista_adx_resp.end();
    double ad1=0; // Como os ultimos valores poderao ser preenchidos com 0
    double ad2=0; // estas variaveis sao utilizadas neste contreole para que
    double ad3=0; // no lugar do zero seja armazenado o ultimo valor (x e y) valido
    if (adx_periodo < intervalo){
        QwtArray<QwtDoublePoint> adx1(intervalo-adx_periodo-1);
        QwtArray<QwtDoublePoint> adx2(intervalo-adx_periodo-1);
        QwtArray<QwtDoublePoint> adx3(intervalo-adx_periodo-1);
        while (iter_2 != lista_adx_resp.begin())
        {
            objeto2 = *iter_2;
            ad1 = objeto2->IDneg == 0 ? ad1 : objeto2->IDneg;
            ad2 = objeto2->IDpos == 0 ? ad2 : objeto2->IDpos;
            ad3 = objeto2->resADX == 0 ? di3 : objeto2->resADX;
            x1 = objeto2->IDneg == 0 ? x1 : x;
            x2 = objeto2->IDpos == 0 ? x2 : x;
            x3 = objeto2->resADX == 0 ? x3 : x;
            adx1[x] = QwtDoublePoint((double) x1, ad1);
            adx2[x] = QwtDoublePoint((double) x2, ad2);
            adx3[x] = QwtDoublePoint((double) x3, ad3);
            iter_2--;
            x++;
        }
        for(i = 0; i < adx_periodo; i++){
            adx3[i] = adx3[adx_periodo];
        }
        for(i = 0; i < (int) adx_periodo/2; i++){
            adx2[i] = adx2[(int) adx_periodo/2];
            adx1[i] = adx1[(int) adx_periodo/2];
        }
        qwtPlot_4->setData(&adx2, &adx1, &adx3);
        qwtPlot_4->replot();
    }
    x=0;
    //END ADX

    //TRIX

    double tr_fechamento[intervalo];
    double est_minimo[intervalo];
    double est_maximo[intervalo];
    for (i = 0 ; i < intervalo ; i++){
        tr_fechamento[i] = data_db.at((intervalo -i)+ponteiro).close;
        est_minimo[i] = data_db.at((intervalo -i)+ponteiro).low;
        est_maximo[i] = data_db.at((intervalo -i)+ponteiro).high;
    }

    Trix *trix = new Trix;
    //    trix_n_dias = sb_trix1->value();
    //    trix_q_dias = sb_trix2->value();
    trix->calculoTrix(tr_fechamento,intervalo,trix_n_dias,trix_q_dias);//periodo = 13
    QwtArray<QwtDoublePoint> trix1(intervalo-trix_n_dias*3+2);
    QwtArray<QwtDoublePoint> ma(intervalo-4);
    double trix4[intervalo];
    double max[intervalo];

    for (int i =0; i < intervalo; i++){
        trix4[i] = trix->trix4[intervalo - i];
        max[i] = trix->ma[intervalo - i];
    }

    for(int i = 0; i < intervalo-trix_n_dias*3+2; i++){
        trix1[i] = QwtDoublePoint((double) i+trix_n_dias*3+2, trix4[i+trix_n_dias*3+2]);
    }
    for(int i = 0; i < intervalo-4; i++){
        ma[i] = QwtDoublePoint((double) i+4, max[i+4]);
    }
    qwtPlot_2->setData(&ma, &trix1);
    qwtPlot_2->replot();
    //END TRIX

    //estocastico
    Estocastico calcula_estocastico;
    calcula_estocastico.CalculaEstocastico(tr_fechamento, intervalo, est_maximo, est_minimo, est_periodo);
    QwtArray<QwtDoublePoint> est_k(intervalo);
    QwtArray<QwtDoublePoint> est_d(intervalo);
    QwtArray<QwtDoublePoint> est_8(intervalo);
    QwtArray<QwtDoublePoint> est_2(intervalo);

    double *ret_estocastico_k = calcula_estocastico.linhaK;
    double *ret_estocastico_d = calcula_estocastico.linhaD;

    for(int i = 0; i < intervalo; i++){
        est_k[i] = QwtDoublePoint((double) i, ret_estocastico_k[intervalo - i]);
        est_d[i] = QwtDoublePoint((double) i, ret_estocastico_d[intervalo - i]);
        est_8[i] = QwtDoublePoint((double) i, (double) 80);
        est_2[i] = QwtDoublePoint((double) i, (double) 20);
    }
    for(int i = 0; i < est_periodo+1; i++){
        est_k[i] = est_k[est_periodo+1] ;
    }
    for(int i = 0; i < 2*est_periodo+1; i++){
        est_d[i] = est_d[2*est_periodo];
    }

    qwtPlot_5->setData(&est_k, &est_d, &est_8, &est_2);
    qwtPlot_5->replot();

    //end estocastico

    dock1->setWindowTitle("CandleStick + Bandas de Boillinger - [" + toDateTime(datas[0]) + ", "+ toDateTime(datas[(int)datas.size()-2])+"]");
    dock2->setWindowTitle("DIDI - [" + toDateTime(datas[0]) + ", "+ toDateTime(datas[(int)datas.size()-2])+"] ciano - baixa; amarelo - alta; cinza - base");
    dock3->setWindowTitle("TRIX - [" + toDateTime(datas[0]) + ", "+ toDateTime(datas[(int)datas.size()-2])+"] amarelo - ma4; cinza - trix9");
    dock4->setWindowTitle("ADX - [" + toDateTime(datas[0]) + ", "+ toDateTime(datas[(int)datas.size()-2])+"] cinza - ADX; amarelo - DI-; ciano - DI+");
    dock5->setWindowTitle("ESTOCASTICO - [" + toDateTime(datas[0]) + ", "+ toDateTime(datas[(int)datas.size()-2])+"] ciano - %K8; amarelo - %D8");
}

QString Interface::toDateTime(QwtDoubleInterval minValue){
    int unixTime = minValue.maxValue();
    QDateTime timestamp;
    timestamp.setTime_t(unixTime);
    return timestamp.toString("dd/MM/yy");
}

/*Esse metdo serah utilizado na traduçao do aplicativo para uma outra lingua*/
void Interface::retranslateUi()
    {
    this->setWindowTitle(QApplication::translate("Candelabro", "Candelabro", 0, QApplication::UnicodeUTF8));
    actionFechar->setText(QApplication::translate("Fechar", "Fechar", 0, QApplication::UnicodeUTF8));
    mainBox->setTitle(QString());
    boxIntervalo->setTitle(QApplication::translate("Intervalo (dias)", "Intervalo (dias)", 0, QApplication::UnicodeUTF8));
    labelBox->setText(QString());
    boxAcao->setTitle(QApplication::translate("Papel", "Papel", 0, QApplication::UnicodeUTF8));
    menuArquivo->setTitle(QApplication::translate("Arquivo", "Arquivo", 0, QApplication::UnicodeUTF8));
    dock2->setWindowTitle(QApplication::translate("dock2", "dock2", 0, QApplication::UnicodeUTF8));
    dock3->setWindowTitle(QApplication::translate("doc3", "doc3", 0, QApplication::UnicodeUTF8));
    dock4->setWindowTitle(QApplication::translate("doc4", "doc4", 0, QApplication::UnicodeUTF8));
    dock5->setWindowTitle(QApplication::translate("doc5", "doc5", 0, QApplication::UnicodeUTF8));
    slider->setWindowTitle(QApplication::translate("Slider", "Slider", 0, QApplication::UnicodeUTF8));
} // retranslateUi




void Interface::atualizarBoxAcao()
{
    QObject::disconnect(this->comboAcao, SIGNAL(currentIndexChanged(int)), this, SLOT(mudarAcaoDaTela()));
    this->comboAcao->clear();
    this->comboAcao->addItems(db->getPricedStocksNames());
    QObject::connect(this->comboAcao, SIGNAL(currentIndexChanged(int)), this, SLOT(mudarAcaoDaTela()));
    mudarAcaoDaTela();
}
